var SerialPort = require("serialport");
var config = require("../config/config");
var socket = require("./socket");
var parseMessage = require('./parseMessage');
var db = require("./db");
var util = require("./util");

var dataStore = "";
var serial_number = 0;

global.serialport = new SerialPort(config.serial_port, {
    autoOpen: true,
    baudRate: 115200,
    dataBits: 8,
    hupcl: true,
    lock: true,
    parity: 'none',
    rtscts: false,
    stopBits: 1,
    xany: false,
    xoff: false,
    xon: false,
    highWaterMark: 64 * 1024
}); // this is the openImmediately flag [default is true]

// open errors will be emitted as an error event
serialport.on('error', function(err) {
    console.log('Error: ', err.message);
});

var parseSinglePackage = function (data) {
    var dataContent = data.split("*");
    if(dataContent.length == 2){ //单个报文必须是内容*校验码
        // if(util.makeCheckSum(util.string216Str(dataContent[0])) == dataContent[1]){
        var a111 = util.makeCheckSum(util.string216Str(dataContent[0]));
        var b111 = dataContent[1].substr(0,2);
        if(a111 == b111){
            serial_number++;
            console.log("解析渔船上传的第"+serial_number+"信息：$" + data);
            var dataByte = data.split(",");
            if(dataByte[0] == 'BDTXR'){ //判断是什么信息，$BDTXR北斗短报文
                var content = parseMessage.parseUploadMessage(data);
                if(socket.socketArray.length != 0){
                    for(var i = 0; i < socket.socketArray.length; i++){
                        socket.socketArray[i].write(content);
                    }
                }
            }else if((dataByte[0] == 'BDFKI') && (dataByte[2] == "Y")){ //判断串口回复
                db.downMessage.update({
                    state:'1'
                },{
                    where:{
                        id: global.downMsg.id,
                        receiver:global.downMsg.receiver
                    }
                }).then(function(result){
                    if(result == "1"){
                        console.log('updated user为1成功');
                    }
                });
            }

            return true;
        }
    }

    return false;
}
var parseMultiPackage = function (data) {
    var ifParse = false;
    var dataArray = data.split("$");

    if(dataArray.length == 1){
        ifParse = parseSinglePackage(dataArray[0]);
        if(ifParse){
            dataStore = "";
        };
    }else{
        for(var i = 0; i < dataArray.length; i++){
            ifParse = parseSinglePackage(dataArray[i]);
        }
        if(!ifParse){
            dataStore = dataArray[dataArray.length - 1];
        }else {
            dataStore = "";
        }
    }
}

serialport.on('data', function (data) {
    var dataString = data.toString();
    console.log("串口接收到的信息：" + dataString);
    dataStore += dataString;

    parseMultiPackage(dataStore);

    receiveTime = new Date().getTime();
});


